package com.vm.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.vm.fragment.UIHelper;
import com.vm.utils.ApkUtils;
import com.vm.utils.SoftDataUtil;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "InflateParams", "DefaultLocale" })
public class PackageManagerActivity extends Activity {
	CheckBox checkbox;
	LinearLayout found_ll_1;
	TextView tv_all1;
	TextView tv_all3;
	Button btn_clean;
	ImageView imgbtn_search_back;
	private List<String> apklist = new ArrayList<String>(); // 结果 List
	long totalsize;
	List<String> list;
	private List<String> getFiles = new ArrayList<String>();
	private static final int COMPLETED = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.installation_package_manage);
		init();
		list = new ArrayList<String>();
		lazyLoad();
	}

	protected void lazyLoad() {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				UIHelper.showDialogForLoading(PackageManagerActivity.this,
						"搜索中...", false);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(300);
					// 在这里添加调用接口获取数据的代码
					initData();
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功

				} else {
					// 加载失败
				}
				// 关闭对话框

			}
		}.execute();
	}

	// 主线程更新视图
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == COMPLETED) {
				for (String string : getFiles) {
					System.out.println(string);
					found_ll_1.addView(dyAddView(string));
				}

				String formatSize = SoftDataUtil.formatSize(totalsize);
				tv_all3.setText(formatSize);
				tv_all1.setText(Integer.toString(getFiles.size()));
			}
		}
	};

	// 开启新线程加载,完成后给handle发送消息
	public void initData() {
		Thread t = new Thread() {
			public void run() {
				getFiles = GetFiles(Environment.getExternalStorageDirectory()
						+ "/", ".apk", true);
				UIHelper.hideDialogForLoading();
				Message msg = new Message();
				msg.what = COMPLETED;
				handler.sendMessage(msg);
			}
		};
		t.start();

	}

	public LinearLayout dyAddView(final String absPath) {
		LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(
				R.layout.installation_package_manage_item, null);
		CheckBox checkbox_set = (CheckBox) linearLayout
				.findViewById(R.id.checkbox_set);
		ImageView iv_softImage = (ImageView) linearLayout
				.findViewById(R.id.iv_softImage);
		TextView tv_softName = (TextView) linearLayout
				.findViewById(R.id.tv_softName);
		TextView tv_now_version_number = (TextView) linearLayout
				.findViewById(R.id.tv_now_version_number);
		TextView tv_softSize = (TextView) linearLayout
				.findViewById(R.id.tv_softSize);
		Button btn_install = (Button) linearLayout
				.findViewById(R.id.btn_install);
		Button btn_uninstall = (Button) linearLayout
				.findViewById(R.id.btn_uninstall);
		if (checkbox_set.isChecked()) {
			list.add(absPath);
		}
		checkbox_set.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					list.add(absPath);
				} else {
					list.remove(absPath);
				}
			}
		});
		if (absPath != null) {
			PackageManager pm = this.getPackageManager();
			PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath,
					PackageManager.GET_ACTIVITIES);
			final File file = new File(absPath);
			if (file.exists()) {
				long mylength = file.length();
				totalsize += file.length();
				String size = SoftDataUtil.formatSize(mylength);
				tv_softSize.setText(size);
			}
			if (pkgInfo != null) {
				ApplicationInfo appInfo = pkgInfo.applicationInfo;
				appInfo.sourceDir = absPath;
				appInfo.publicSourceDir = absPath;
				String packageName = appInfo.packageName; // 得到包名
				if (ApkUtils.isAppInstalled(packageName,
						PackageManagerActivity.this)) {
					btn_install.setVisibility(View.VISIBLE);
					btn_uninstall.setVisibility(View.GONE);
				} else {
					btn_install.setVisibility(View.GONE);
					btn_uninstall.setVisibility(View.VISIBLE);
				}
				btn_uninstall.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (file.exists()) {
							Intent i = new Intent(Intent.ACTION_VIEW);
							i.setDataAndType(
									Uri.parse("file://" + file.toString()),
									"application/vnd.android.package-archive");
							startActivity(i);
						}
					}
				});
				String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
				tv_softName.setText(appName);
				String version = pkgInfo.versionName; // 得到版本信息
				tv_now_version_number.setText(version);
				/* icon1和icon2其实是一样的 */
				Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息
				iv_softImage.setImageDrawable(icon1);
			} else {
				tv_softName.setText(file.getName());
				iv_softImage.setImageResource(R.drawable.error);
				tv_now_version_number.setText("破损文件");
				btn_install.setVisibility(View.GONE);
				btn_uninstall.setVisibility(View.GONE);
			}
		}
		return linearLayout;
	}

	public void init() {
		checkbox = (CheckBox) findViewById(R.id.checkbox);
		found_ll_1 = (LinearLayout) findViewById(R.id.found_ll_1);
		tv_all1 = (TextView) findViewById(R.id.tv_all1);
		tv_all3 = (TextView) findViewById(R.id.tv_all3);
		btn_clean = (Button) findViewById(R.id.btn_clean);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
		btn_clean.setOnClickListener(delete_Listener);
	}

	// 批量删除
	OnClickListener delete_Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			for (int i = 0; i < list.size(); i++) {
				File apkfile = new File(list.get(i));
				apkfile.delete();
			}
			Intent intent = new Intent(PackageManagerActivity.this,
					PackageManagerActivity.class);
			startActivity(intent);
			Toast toast = Toast.makeText(PackageManagerActivity.this, "删除成功",
					Toast.LENGTH_SHORT);
			toast.show();
			finish();
		}

	};
	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	// 搜索目录，扩展名(判断的文件类型的后缀名)，是否进入子文件夹
	public List<String> GetFiles(String Path, String Extension,
			boolean IsIterative) {
		File[] files = new File(Path).listFiles();
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isFile()) {
				if (f.getPath()
						.substring(f.getPath().length() - Extension.length())
						.equals(Extension)) // 判断扩展名
					apklist.add(f.getPath());
				if (!IsIterative)
					break; // 如果不进入子集目录则跳出
			} else if (f.isDirectory() && f.getPath().indexOf("/.") == -1) // 忽略点文件（隐藏文件/文件夹）
				GetFiles(f.getPath(), Extension, IsIterative); // 这里就开始递归了
		}
		return apklist;
	}
}